import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Select, Modal } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryEquipmentListParams, Equipment } from './services';
import { EquipmentStatus, queryEquipmentList, EquipmentType, VinStatus } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import StubModal, { StubModalProps } from './components/StubModal';
import StationSelect from '@/components/StationSelect';
import { jump2target } from '@/utils/common';
import dayjs from 'dayjs';
import { CheckCircleFilled } from '@ant-design/icons';
import { exportEquipment, exportStation } from '@/pages/order/chargeOrder/services';
import OrgSelect from '@/components/OrgSelect';

const EquipmentPage: React.FC<RoutePageProps> = (props) => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm<any>()
  const expReq = useRequest(exportEquipment, {manual: true})
  const [searchParams, setSearchParams] = useState<QueryEquipmentListParams>({
    pageNum: 1, pageSize: 10,
  })
  const stubList = useRequest(() => queryEquipmentList(searchParams), {
    refreshDeps: [searchParams],
  })
  const [stubModalProps, setStubModalProps] = useState<StubModalProps>({open: false})

  const onStubModalCancel = () => {
    setStubModalProps({open: false})
  }

  const openStubModal = (record: Equipment) => {
    jump2target(`/station/stubIdList?equipmentId=${record.id}`, {needRefresh: true})
    // setStubModalProps({open: true, stationId: record.stationId, equipmentId: record.id})
  }

  const exportExcel = () => {
    const formValues = searchForm.getFieldsValue()
    const _params = {
      ...searchParams,
      stationTitle: formValues.station?.[0]?.name,
      stubType: formValues.stubType,
      isStock:formValues.isStock,
      equipmentId: formValues.equipmentId,
      stubName: formValues.stubName,
      status: formValues.status,
      orgId: formValues.org?.id,
    }
    expReq.runAsync(_params)
      .then(res => {
        Modal.confirm({
          icon: <CheckCircleFilled style={{color: 'red'}} />,
          content: '导出申请成功，请前往导出记录查看文档。',
          onOk: () => {
            jump2target('/report/exportUrl')
          }
        })
      })
  }

  const openEditPage = (title: string, type: string, record?: Equipment) => {
    sessionStorage.stub = JSON.stringify(record)
    jump2target(`/station/stubList/edit?type=${type}&id=${record?.id || ''}`, {
      needRefresh: true
    })
    sessionStorage.setItem('__/station/stubList/edit_title', title)
  }

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      stationTitle: formValues.station?.[0]?.name,
      stubType: formValues.stubType,
      isStock:formValues.isStock,
      equipmentId: formValues.equipmentId,
      stubName: formValues.stubName,
      status: formValues.status,
      orgId: formValues.org?.id,
      pageNum: 1,
    })
  }

  const columns: ColumnsType<Equipment> = [
    {
      title: '设备编号',
      dataIndex: 'id',
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    // {
    //   title: '仓库状态',
    //   dataIndex: 'stationId',
    //   render: val => val === null ? '在' : '不在',
    // },
    {
      title: '所属场站',
      dataIndex: 'stationName',
    },
    {
      title: '所属经销商',
      dataIndex: 'orgName',
    },
    {
      title: '支持vin',
      dataIndex: 'vinStatus',
      render: val => val === VinStatus.支持 ? '支持' : '不支持',
    },
    {
      title: '设备类型',
      dataIndex: 'type',
      render: val => val && EquipmentType[val]
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      render: val => val && EquipmentStatus[val]
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 140,
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 150,
      fixed: 'right',
      render: (id: number, record) => {
        return <Space>
          <a onClick={() => openStubModal(record)}>枪列表</a>
          <a onClick={() => openEditPage('设备详情', 'look', record)}>详情</a>
          <Access accessible={!record.operationId}>
            <a onClick={() => openEditPage('编辑设备', 'edit', record)}>编辑</a>
          </Access>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const { stationId, stationName } = props.params
    if (stationName) {
      searchForm.setFieldsValue({station: [{id: stationId, name: stationName}]})
      onFinish({station: [{id: stationId, name: stationName}]})
    }
  }, [props.params.stationName])

  useEffect(() => {
    const refresh = () => {
      stubList.refresh()
    }
    window.addEventListener('refreshEquipmentList', refresh)
    return () => {
      window.removeEventListener('refreshEquipmentList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('添加设备', 'edit')}>添加设备</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchEquipmentForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='电站名称' name='station'>
                  <StationSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备类型' name='stubType'>
                  <Select placeholder='请选择' options={enum2options(EquipmentType)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='仓库状态' name='isStock'>
                  <Select placeholder='请选择' options={[
                    {label: '在', value: 1},
                    {label: '不在', value: 2},
                  ]} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备ID' name='equipmentId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备名称' name='stubName'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='经销商ID' name='org'>
                  <OrgSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(EquipmentStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={stubList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                  <Button onClick={exportExcel} loading={expReq.loading}>导出</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Equipment>
          rowKey='id'
          loading={stubList.loading}
          dataSource={stubList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: stubList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <StubModal
        {...stubModalProps}
        onCancel={onStubModalCancel}
      />
    </div>
  );
};

export default EquipmentPage;
